package client;

import beans.Estudiant;
import common.EOlympicsException;
import common.RemotInterface;
import common.TDSLanguageUtils;
import java.net.URL;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 * Classe Client
 * @author Juan Luís Chávez Lobato i Jesús Hernàndez Garcia
 */

public class Client extends javax.swing.JFrame {

    private RemotInterface remot;
    
    /**
     * Creates new form Client
     */
    public Client() {
        initComponents();
        setTitle(TDSLanguageUtils.getMessage("titol.finestra"));
        jLabelEstCon.setText(TDSLanguageUtils.getMessage("texte.estudiant"));
        BotoConnectar.setText(TDSLanguageUtils.getMessage("boto.connectar"));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BotoConnectar = new javax.swing.JButton();
        jLabelEstCon = new javax.swing.JLabel();
        jTFLogin = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        BotoConnectar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        BotoConnectar.setText("Connectar Servidor RMI");
        BotoConnectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotoConnectarActionPerformed(evt);
            }
        });

        jLabelEstCon.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabelEstCon.setText("Estudiant connectat : ");

        jTFLogin.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTFLogin.setText("login1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelEstCon)
                .addGap(29, 29, 29)
                .addComponent(jTFLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(BotoConnectar, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BotoConnectar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelEstCon)
                    .addComponent(jTFLogin))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BotoConnectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotoConnectarActionPerformed
        // Connectar amb el Servidor RMI i verificar que l'estudiant existeix
        // a la BD.
        try {
            Properties prop = new Properties();
            URL url = ClassLoader.getSystemResource("properties/configuration.properties");
            prop.load(url.openStream());
            remot = (RemotInterface) Naming.lookup(prop.getProperty("pathrmi"));

            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("missatge.client.connectat"),
                    TDSLanguageUtils.getMessage("missatge.connexio"),
                    JOptionPane.INFORMATION_MESSAGE);
            
            // Comprovar que l'estudiant és a la BD
            Estudiant est = remot.getEstudiant(jTFLogin.getText());            
        
            if (null != est) {
                if (remot.haFetElQuestionari(jTFLogin.getText())) {
                    JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("missatge.client.QuestFet"),
                            est.getNom() + " " + est.getCognoms(),
                            JOptionPane.INFORMATION_MESSAGE);
                    new client.PantallaResultats(remot, est).setVisible(true);
                } else {
                    new client.PantallaParticipacio(remot, est).setVisible(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("missatge.client.EstNoTrobat"),
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
                
        } catch (RemoteException e) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, e);
            JOptionPane.showMessageDialog
                    (null, TDSLanguageUtils.getMessage("ERR_REMOT"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, e);
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }//GEN-LAST:event_BotoConnectarActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        dispose();
        System.exit(0);
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TDSLanguageUtils.setDefaultLanguage("i18n/messages");
                new Client().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotoConnectar;
    private javax.swing.JLabel jLabelEstCon;
    private javax.swing.JTextField jTFLogin;
    // End of variables declaration//GEN-END:variables
}
